﻿#include "equipmentlist.h"
#include "ui_equipmentlist.h"
#include "rtfform.h"

equipmentList::equipmentList(QWidget *parent) :
    QFrame(parent),
    ui(new Ui::equipmentList)
{
    ui->setupUi(this);
    fillStuff();
    showAll=false;

    dbModel = new myDataModel(this,ui->table,getQuery());

    dbModel->setHeader(QStringList()<<"№"<<"Принят"<<"Оборудование"<<"S/N"<<"Причина"<<"Результат"<<"Клиент"<<"Выдан"<<"Примечание"<<"Сотрудник");

    ui->table->setColumnHidden( EDB_attention, true);
    ui->table->show();
    ui->table->scrollTo(dbModel->index(dbModel->rowCount()-1,0));

    connect(ui->table->selectionModel(), SIGNAL(currentRowChanged ( const QModelIndex &, const QModelIndex &)),
            this, SLOT(currentRowChanged( const QModelIndex &, const QModelIndex &)));

    ui->table->horizontalHeader()->setResizeMode(EDB_enumber,QHeaderView::ResizeToContents);
    ui->table->horizontalHeader()->setResizeMode(EDB_indate,QHeaderView::ResizeToContents);
    ui->table->horizontalHeader()->setResizeMode(EDB_outdate,QHeaderView::ResizeToContents);
    ui->table->horizontalHeader()->setResizeMode(EDB_who,QHeaderView::ResizeToContents);
    ui->table->horizontalHeader()->setResizeMode(EDB_name,QHeaderView::Stretch);
    ui->table->horizontalHeader()->setResizeMode(EDB_client,QHeaderView::Stretch);
    ui->table->horizontalHeader()->setResizeMode(EDB_problem,QHeaderView::Stretch);
    ui->table->horizontalHeader()->setResizeMode(EDB_serial,QHeaderView::Stretch);
    ui->table->horizontalHeader()->setResizeMode(EDB_result,QHeaderView::Stretch);
    ui->table->horizontalHeader()->setResizeMode(EDB_comment,QHeaderView::Stretch);

}

equipmentList::~equipmentList()
{
    delete ui;
    delete dbModel;
}

void equipmentList::updateList()
{
       dbModel->setQuery(getQuery());
       ui->table->scrollTo(dbModel->index(dbModel->rowCount()-1,0));
}

void equipmentList::currentRowChanged(const QModelIndex &current, const QModelIndex &previous)
{
    ui->equipmentEdit->setText(dbModel->getData(EDB_name));
    ui->problemEdit->setText(dbModel->getData(EDB_problem));
    ui->clientEdit->setText(dbModel->getData(EDB_client));
    ui->serialEdit->setText(dbModel->getData(EDB_serial));
    ui->resultEdit->setText(dbModel->getData(EDB_result));
    ui->commentEdit->setText(dbModel->getData(EDB_comment));
    ui->whoSelect->setEditText(dbModel->getData(EDB_who));
}

void equipmentList::on_showallButton_clicked()
{
    showAll=!showAll;
    dbModel->setQuery(getQuery());
    ui->showallButton->setText(showAll?"Текущее":"Все");
}


QString equipmentList::getQuery()
{
    return showAll?\
                "SELECT * FROM EquipmentList;":\
                "SELECT * FROM EquipmentList WHERE outdate is null;";
}


void equipmentList::fillStuff()
{
    QSqlQuery query("SELECT * FROM stafflist ORDER by who DESC");
    while(query.next())ui->whoSelect->insertItem(0,query.value(0).toString());

}

void equipmentList::on_searchButton_clicked()
{
    dbModel->setFilterFixedString(ui->searchEdit->text());
}

void equipmentList::on_searchEdit_returnPressed()
{
    dbModel->setFilterFixedString(ui->searchEdit->text());
}


void equipmentList::on_delSearchButton_clicked()
{
    ui->searchEdit->clear();
    dbModel->setFilterFixedString("");
}

void equipmentList::on_printButton_clicked()
{
    if(ui->table->currentIndex().row()<0)return;
    QMap<QString,QString> formdata;
    formdata["<enumber>"]=dbModel->getData(EDB_enumber);
    formdata["<ename>"]=dbModel->getData(EDB_name);
    formdata["<serial>"]=dbModel->getData(EDB_serial);
    formdata["<indate>"]=dbModel->getData(EDB_indate);
    formdata["<client>"]=dbModel->getData(EDB_client);
    formdata["<comment>"]=dbModel->getData(EDB_comment);
    formdata["<problem>"]=dbModel->getData(EDB_problem);
    formdata["<worker>"]=dbModel->getData(EDB_who);
    rtfForm rtf(QApplication::applicationDirPath()+"\\equipment.rtf",formdata);
}

void equipmentList::on_doneButton_clicked()
{
    if(ui->table->currentIndex().row()<0)return;
    QSqlQuery query;
    query.prepare("UPDATE equipmentlist SET outdate=:outdate WHERE enumber=:number");
    query.bindValue(":outdate",dbModel->getData(EDB_outdate).isEmpty()?QDate::currentDate():QDate::QDate());
    query.bindValue(":number",dbModel->getData(EDB_enumber));
    query.exec();

    if(query.lastError().isValid())QMessageBox::warning(0,"Неверный запрос",query.lastError().text());

    dbModel->setQuery(getQuery());
}

void equipmentList::on_addButton_clicked()
{
    if(ui->equipmentEdit->text().isEmpty()){
        QMessageBox::warning(0,"Ошибка","Введите название оборудования.");
        return;
    }
    QSqlQuery query;
    query.prepare("INSERT INTO equipmentlist "
                  "VALUES (DEFAULT,:indate,:name,:serial,:problem,:result,:client,NULL,:comment,:who)");
    query.bindValue(":indate",QDate::currentDate());
    query.bindValue(":name",ui->equipmentEdit->text());
    query.bindValue(":serial",ui->serialEdit->text());
    query.bindValue(":problem",ui->problemEdit->text());
    query.bindValue(":result",ui->resultEdit->text());
    query.bindValue(":client",ui->clientEdit->text());
    query.bindValue(":comment",ui->commentEdit->text());
    query.bindValue(":who",ui->whoSelect->currentText());
    query.exec();

    if(query.lastError().isValid())QMessageBox::warning(0,"Неверный запрос",query.lastError().text());

    dbModel->itemAdded();

}

void equipmentList::on_changeButton_clicked()
{
    if(ui->equipmentEdit->text().isEmpty()){
        QMessageBox::warning(0,"Ошибка","Введите название оборудования.");
        return;
    }

    QSqlQuery query;
    query.prepare("UPDATE equipmentlist "
                  "SET name=:name, serial=:serial, problem=:problem, result=:result, client=:client, comment=:comment, who=:who "
                  "WHERE enumber=:number");

    query.bindValue(":name",ui->equipmentEdit->text());
    query.bindValue(":serial",ui->serialEdit->text());
    query.bindValue(":problem",ui->problemEdit->text());
    query.bindValue(":result",ui->resultEdit->text());
    query.bindValue(":client",ui->clientEdit->text());
    query.bindValue(":comment",ui->commentEdit->text());
    query.bindValue(":who",ui->whoSelect->currentText());
    query.bindValue(":number",dbModel->getData(EDB_enumber));
    query.exec();

    if(query.lastError().isValid())QMessageBox::warning(0,"Неверный запрос",query.lastError().text());

    dbModel->itemChanged();
}


void equipmentList::on_exportButton_clicked()
{

    QString excelFilePath=QApplication::applicationDirPath()+"\\equipment.xls";
    QTemporaryFile *tempfile=new QTemporaryFile(QDir::tempPath() + QDir::separator() + "XXXXXX.xls");
    tempfile->open();
    QString resname= tempfile->fileName();
    delete tempfile;
    if(!QFile::copy(excelFilePath,resname)){
       QMessageBox::warning(0,"Немогу создать файл",resname);
       return;
    }
    QString strDBName = QString("DRIVER={Microsoft Excel Driver (*.xls)};FIL={MS Excel};READONLY=FALSE;DBQ="+resname);
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC","xls_db");
    db.setDatabaseName(strDBName);
    if (!(db.open())){
        QMessageBox::warning(0,"Ошибка создания отчета",db.lastError().text());
        return;
    }

//    query.exec("CREATE TABLE `report` (Номер NUMBER,Принят TEXT,Оборудование TEXT,Серийник TEXT,Причина TEXT,Результат TEXT,Клиент TEXT,Выдан TEXT,Примечание TEXT,Сотрудник TEXT)");
//    if(query.lastError().isValid())QMessageBox::warning(0,"Неверный запрос",query.lastError().text());
//    query.clear();

    for(int r=0;r<dbModel->rowCount();r++){
    QSqlQuery query(db);
    query.prepare("INSERT INTO report "
                  "VALUES (:enumber,:indate,:name,:serial,:problem,:result,:client,:outdate,:comment,:who)");
    query.bindValue(":enumber",dbModel->data(dbModel->index(r,EDB_enumber)).toInt());
    query.bindValue(":indate",dbModel->data(dbModel->index(r,EDB_indate)).toString());
    query.bindValue(":name",dbModel->data(dbModel->index(r,EDB_name)).toString());
    query.bindValue(":serial",dbModel->data(dbModel->index(r,EDB_serial)).toString());
    query.bindValue(":problem",dbModel->data(dbModel->index(r,EDB_problem)).toString());
    query.bindValue(":result",dbModel->data(dbModel->index(r,EDB_result)).toString());
    query.bindValue(":client",dbModel->data(dbModel->index(r,EDB_client)).toString());
    query.bindValue(":outdate",dbModel->data(dbModel->index(r,EDB_outdate)).toString());
    query.bindValue(":comment",dbModel->data(dbModel->index(r,EDB_comment)).toString());
    query.bindValue(":who",dbModel->data(dbModel->index(r,EDB_who)).toString());
    query.exec();
    if(query.lastError().isValid()){
        QMessageBox::warning(0,"Неверный запрос",query.lastError().text());
        break;
    }
    query.clear();
}


    db.close();
    QSqlDatabase::removeDatabase("xls_db");

    QDesktopServices::openUrl(QUrl("file:///"+resname));
}
